package org.summer.generator.resolver;

import lombok.RequiredArgsConstructor;
import org.summer.generator.DataTypeConverter;
import org.summer.generator.StringUtil;
import org.summer.generator.TableConstants;
import org.summer.generator.log.Logger;
import org.summer.generator.log.LoggerManager;
import org.summer.generator.vo.Column;
import org.summer.generator.vo.Table;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库数据表到Table对象解析器,需要一个Connection对象
 */
@RequiredArgsConstructor
public class TableResolver {
    private static final Logger log = LoggerManager.getLogger(TableResolver.class);
    private final Connection connection;

    /**
     * 根据数据表明解析出Table对象
     */
    public Table parseTableFormTableName(String tableName) {
        try {
            return parseTable(tableName);
        } catch (SQLException e) {
            log.error("解析数据表" + tableName + "出现错误", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析数据表信息
     * @param tableName
     * @return
     * @throws SQLException
     */
    private Table parseTable(String tableName) throws SQLException {
        log.debug("根据数据表名解析Table对象： " + tableName);
        ResultSet tableResultSet = this.connection.getMetaData()
                .getTables(connection.getCatalog(), null, tableName, null);
        if (tableResultSet.next()){
            Table table = new Table();
            String tn = tableResultSet.getString(TableConstants.TABLE_NAME);
            table.setDatabaseName(tableResultSet.getString(TableConstants.TABLE_CAT));
            table.setTableName(tn);
            table.setRemark(tableResultSet.getString(TableConstants.REMARKS));
            table.setTableLowerName(StringUtil.underlineCaseLowerCamel(tn));
            table.setTableUpperName(StringUtil.underlineCaseUpperCamel(tn));
            log.debug("解析出Table数据：" + table);
            table.setColumns(parseColumn(tableName));
            return table;
        }
        return null;
    }

    /**
     * 解析数据表列信息
     */
    private List<Column> parseColumn(String tableName) throws SQLException {
        ResultSet res = connection.getMetaData().getColumns(connection.getCatalog(), null, tableName, null);
        List<Column> columns = new ArrayList<>();
        while (res.next()){
            int dataType = res.getInt(TableConstants.COLUMN_DATA_TYPE);
            String autoincrement = res.getString(TableConstants.COLUMN_IS_AUTOINCREMENT);
            Column c = new Column();
            c.setColumnName(StringUtil.underlineCaseLowerCamel(res.getString(TableConstants.COLUMN_NAME)));
            c.setDataType(dataType);
            c.setJavaType(DataTypeConverter.convertToJavaType(dataType));
            c.setTsType(DataTypeConverter.convertToTypescript(dataType));
            c.setTypeName(res.getString(TableConstants.COLUMN_TYPE_NAME));
            c.setColumnSize(res.getInt(TableConstants.COLUMN_SIZE));
            c.setDecimalDigits(res.getString(TableConstants.COLUMN_DECIMAL_DIGITS));
            c.setNullable(res.getInt(TableConstants.COLUMN_NULLABLE));
            c.setIsNullable(res.getString(TableConstants.COLUMN_IS_NULLABLE));
            c.setDefaultValue(res.getString(TableConstants.COLUMN_DEF));
            c.setOrdinalPosition(res.getInt(TableConstants.COLUMN_ORDINAL_POSITION));
            c.setRemark(res.getString(TableConstants.REMARKS));
            c.setAutoincrement("YES".equals(autoincrement));
            columns.add(c);
//            log.debug("解析数据表字段%s： ".formatted(c.getColumnName()) + c);
        }
        return columns;
    }
}
